<template>
  <div class="book-form">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>{{ isEdit ? '编辑图书' : '添加图书' }}</h2>
      <el-button @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
    </div>

    <!-- 表单区域 -->
    <div class="form-section">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="book-form-content"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图书标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入图书标题"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ISBN" prop="isbn">
              <el-input
                v-model="formData.isbn"
                placeholder="请输入ISBN"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input
                v-model="formData.author"
                placeholder="请输入作者"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社" prop="publisher">
              <el-input
                v-model="formData.publisher"
                placeholder="请输入出版社"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-input
                v-model="formData.category"
                placeholder="请输入图书分类"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版日期" prop="publishDate">
              <el-date-picker
                v-model="formData.publishDate"
                type="date"
                placeholder="请选择出版日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="formData.price"
                :min="0"
                :precision="2"
                :step="0.1"
                style="width: 100%"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="formData.stock"
                :min="0"
                :step="1"
                style="width: 100%"
                placeholder="请输入库存数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="图书简介" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入图书简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            <el-icon><Check /></el-icon>
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="goBack">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Check, Refresh, Close } from '@element-plus/icons-vue'
import bookApi from '@/api/book'

const router = useRouter()
const route = useRoute()

// 表单引用
const formRef = ref(null)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 提交状态
const submitting = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  title: '',
  isbn: '',
  author: '',
  publisher: '',
  category: '',
  publishDate: '',
  price: null,
  stock: null,
  status: 1,
  description: ''
})

// 表单验证规则
const formRules = reactive({
  title: [
    { required: true, message: '请输入图书标题', trigger: 'blur' },
    { min: 1, max: 200, message: '图书标题长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  isbn: [
    { required: true, message: '请输入ISBN', trigger: 'blur' },
    { min: 10, max: 20, message: 'ISBN长度在 10 到 20 个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { min: 1, max: 100, message: '作者长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  publisher: [
    { required: true, message: '请输入出版社', trigger: 'blur' },
    { min: 1, max: 100, message: '出版社长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入图书分类', trigger: 'blur' },
    { min: 1, max: 50, message: '分类长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量必须大于等于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 返回列表
const goBack = () => {
  router.push('/book')
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  if (!isEdit.value) {
    // 新增模式下重置为默认值
    Object.assign(formData, {
      id: null,
      title: '',
      isbn: '',
      author: '',
      publisher: '',
      category: '',
      publishDate: '',
      price: null,
      stock: null,
      status: 1,
      description: ''
    })
  }
}

// 获取图书详情
const getBookDetail = async (id) => {
  try {
    const result = await bookApi.getById(id)
    if (result) {
      Object.assign(formData, result)
    }
  } catch (error) {
    ElMessage.error('获取图书详情失败: ' + error.message)
    goBack()
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value?.validate()
    if (!valid) return

    submitting.value = true

    if (isEdit.value) {
      // 编辑模式
      await bookApi.update(formData)
      ElMessage.success('更新图书成功')
    } else {
      // 新增模式
      await bookApi.add(formData)
      ElMessage.success('添加图书成功')
    }

    goBack()
  } catch (error) {
    ElMessage.error((isEdit.value ? '更新' : '添加') + '图书失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 组件挂载时的操作
onMounted(() => {
  if (isEdit.value && route.params.id) {
    getBookDetail(route.params.id)
  }
})
</script>

<style scoped>
.book-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-section {
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.book-form-content {
  max-width: 800px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>
